<template>
  <div class="common-layout">
    <el-container>
      <el-header>
      </el-header>
      <el-container>
        <el-aside width="200px" class="sidebar">
          <div class="sidebar-header">
            <h3>消费者功能</h3>
          </div>
          
          <div class="sidebar-menu" v-if="authStore.isLoggedIn">
            <button 
              @click="activeTab = 'changePassword'" 
              :class="{ active: activeTab === 'changePassword' }" 
              class="menu-item"
            >修改密码</button>
            <button 
              @click="activeTab = 'placeOrder'" 
              :class="{ active: activeTab === 'placeOrder' }" 
              class="menu-item"
            >下单</button>
            <button 
              @click="activeTab = 'showGoodsInfo'" 
              :class="{ active: activeTab === 'showGoodsInfo' }" 
              class="menu-item"
            >查看已下单商品信息</button>

          </div>
          
          <div v-else class="sidebar-login-prompt">
            <button @click="goHome" class="back-home-tab">前往登录</button>
          </div>
          
          <!-- 侧边栏底部退出按钮 -->
          <div class="sidebar-footer" v-if="authStore.isLoggedIn">
            <button @click="handleLogout" class="logout-btn">退出登录</button>
          </div>
          
        </el-aside>
        
        <el-main class="main-content">
          <!-- 修改密码表单 -->
          <div v-if="activeTab === 'changePassword'" class="business-card">
            <h3>修改密码</h3>
            <form @submit.prevent="handleChangePassword">
              <input v-model="changePasswordForm.accountId" placeholder="账号" required>
              <input v-model="changePasswordForm.oldPassword" type="password" placeholder="旧密码" required>
              <input v-model="changePasswordForm.newPassword" type="password" placeholder="新密码" required>
              <button type="submit">修改密码</button>
            </form>
          </div>
          
          


          <!-- 下单界面 -->
          <div v-if="activeTab === 'placeOrder'" class="business-card">
            <h3>下单</h3>
            
            <!-- 已上架商品列表 -->
            <div  v-if="!showOrderForm" class="products-section" >
              <h4>已上架商品列表</h4>
              <div v-if="loadingProducts" class="loading">加载中...</div>
              <div v-else-if="availableProducts.length === 0" class="no-products">
                暂无上架商品
              </div>
              <div v-else>
                <!-- 商品表格 -->
                <table class="products-table">
                  <thead>
                    <tr>
                      <th>商品ID</th>
                      <th>商品图片</th>
                      <th>商品名称</th>
                      <th>商品描述</th>
                      <th>单价</th>
                      <th>卖家</th>
                      <th>操作</th>
                    </tr>
                  </thead>
                  <tbody>
                    <tr v-for="product in paginatedProducts" :key="product.listing_id">
                      <td>{{ product.listingId }}</td>
                      <td>
                        <!-- 商品图片 -->
                        <div class="product-images">
                          <img 
                            v-for="(image, index) in getProductImages(product)" 
                            :key="index"
                            :src="image" 
                            :alt="product.productName"
                            class="product-image"
                            @error="handleImageError"
                          />
                          <div v-if="!getProductImages(product) || getProductImages(product).length === 0" class="no-image">
                            暂无图片
                          </div>
                        </div>
                      </td>
                      <td>{{ product.productName }}</td>
                      <td>{{ product.productDescription }}</td>
                      <td>¥{{ product.unitPrice }}</td>
                      <td>{{ product.sellerId }}</td>
                      <td>
                        <button @click="selectProduct(product)" class="select-btn">选择</button>
                      </td>
                    </tr>
                  </tbody>
                </table>
                
                <!-- 分页控件 -->
                <div class="pagination" v-if="totalPages > 1">
                  <button @click="prevPage" :disabled="currentPage === 1" class="pagination-btn">
                    &lt; 上一页
                  </button>
                  <span class="page-info">第 {{ currentPage }} 页 / 共 {{ totalPages }} 页</span>
                  <button @click="nextPage" :disabled="currentPage === totalPages" class="pagination-btn">
                    下一页 &gt;
                  </button>
                </div>
              </div>
            </div>
            
            <!-- 下单表单（在选择商品后显示） -->
            <div v-if="showOrderForm" class="order-form-container">
              <h4>下单信息</h4>
              <form @submit.prevent="handlePlaceOrder" class="order-form">
                <div class="form-group">
                  <label>商品ID:</label>
                  <input v-model="orderForm.goodsId" :placeholder="selectedProduct?.listing_id || '请选择商品'" required readonly>
                </div>
                <div class="form-group">
                  <label>商品名称:</label>
                  <input v-model="orderForm.productName" :placeholder="selectedProduct?.product_name || '请选择商品'" readonly>
                </div>
                <div class="form-group">
                  <label>单价:</label>
                  <input v-model="orderForm.unit_price" :placeholder="selectedProduct?.unit_price || '请选择商品'" readonly>
                </div>
                <div class="form-group">
                  <label>数量:</label>
                  <el-input-number v-model="orderForm.quantity" :min="1" :max="10000" controls-position="right" />
                </div>
                <div class="form-group">
                  <label>收货地址:</label>
                  <input v-model="orderForm.address" placeholder="收货地址" required>
                </div>

                <div class="form-actions">
                  <button type="submit" class="submit-btn">下单</button>
                  <button type="button" @click="cancelOrder" class="cancel-btn">取消</button>
                </div>
              </form>
            </div>
          </div>

          <!-- 查看已下单的商品信息界面 -->
           <div v-if="activeTab === 'showGoodsInfo'" class="business-card"> 
            <h3>查看已下单商品信息</h3>
            <div v-if="loadingOrders" class="loading">加载中...</div>
            <div v-else-if="orderedGoods.length === 0" class="no-products">
              暂无已下单商品
            </div>
            <div v-else>
              <!-- 已下单商品表格 -->
              <table class="products-table">
                <thead>
                  <tr>
                    <th>订单ID</th>
                    <th>商品图片</th>
                    <th>商品名称</th>
                    <th>商品描述</th>
                    <th>单价</th>
                    <th>数量</th>
                    <th>总价格</th>
                    <th>卖家</th>
                    <th>订单状态</th>
                    <th>操作</th>
                  </tr>
                </thead>
                <tbody>
                  <tr v-for="order in paginatedOrders" :key="order.orderId">
                    <td>{{ order.orderId }}</td>
                    <td>
                      <!-- 商品图片 -->
                      <div class="product-images">
                        <img 
                          v-for="(image, index) in getProductImages(order)" 
                          :key="index"
                          :src="image" 
                          :alt="order.productName"
                          class="product-image"
                          @error="handleImageError"
                        />
                        <div v-if="!getProductImages(order) || getProductImages(order).length === 0" class="no-image">
                          暂无图片
                        </div>
                      </div>
                    </td>
                    <td>{{ order.productName }}</td>
                    <td>{{ order.productDescription }}</td>
                    <td>¥{{ order.unitPrice }}</td>
                    <td>{{ order.quantity }}</td>
                    <td>¥{{ (order.unitPrice * order.quantity * 1.15).toFixed(2) }}</td>
                    <td>{{ order.sellerId }}</td>
                    <td>
                      <span :class="{
                        'status-pending': order.orderStatus === 'pending',
                        'status-paid': order.orderStatus === 'paid',
                        'status-shipped': order.orderStatus === 'shipped',
                        'status-completed': order.orderStatus === 'completed',
                        'status-cancelled': order.orderStatus === 'cancelled',
                        'status-returned': order.orderStatus === 'returned'
                      }">
                        {{ getOrderStatusText(order.orderStatus) }}
                      </span>
                    </td>
                    <td>
                      <!-- <button 
                        @click="goToPayment(order)" 
                        class="select-btn"
                        :disabled="order.orderStatus === 'paid'"
                      >
                        去支付
                      </button> -->
                      <!-- 当订单状态为待支付时，才能去支付，当订单状态为已支付时，按钮为可以点击的确认收货 -->
                       <!-- <button 
                        v-if="order.orderStatus === 'pending'" 
                        @click="goToPayment(order)" 
                        class="select-btn"
                      >
                        去支付
                      </button>
                       <button 
                        v-else-if="order.orderStatus === 'paid'" 
                        @click="confirmReceipt(order)" 
                        class="select-btn"
                      >
                        确认收货
                      </button> -->

                      <!-- 设置按钮，点击后跳转到商品详细界面 -->
                      <button @click="viewOrderDetail(order)" class="detail-btn">查看详情</button>
                    

                      
                    </td>
                  </tr>
                </tbody>
              </table>
              
              <!-- 分页控件 -->
              <div class="pagination" v-if="totalOrderPages > 1">
                <button @click="prevOrderPage" :disabled="currentOrderPage === 1" class="pagination-btn">
                  &lt; 上一页
                </button>
                <span class="page-info">第 {{ currentOrderPage }} 页 / 共 {{ totalOrderPages }} 页</span>
                <button @click="nextOrderPage" :disabled="currentOrderPage === totalOrderPages" class="pagination-btn">
                  下一页 &gt;
                </button>
              </div>
            </div>
           </div>

           <!-- 订单详情界面 -->
           <div v-if="activeTab === 'orderDetail'" class="business-card">
            <h3>订单详情</h3>
            <div class="order-detail" v-if="currentOrder">
              <div class="order-info">
                <h4>基本信息</h4>
                <div class="info-row">
                  <span class="label">交易单号：</span>
                  <span class="value">{{ currentOrder.orderId }}</span>
                </div>
                <div class="info-row">
                  <span class="label">商品名称：</span>
                  <span class="value">{{ currentOrder.productName }}</span>
                </div>
                <div class="info-row">
                  <span class="label">商品描述：</span>
                  <span class="value">{{ currentOrder.productDescription }}</span>
                </div>
                <div class="info-row">
                  <span class="label">商品数量：</span>
                  <span class="value">{{ currentOrder.quantity }}</span>
                </div>
                <div class="info-row">
                  <span class="label">单价：</span>
                  <span class="value">¥{{ currentOrder.unitPrice }}</span>
                </div>
                <div class="info-row">
                  <span class="label">交易总金额：</span>
                  <span class="value">¥{{ (currentOrder.unitPrice * currentOrder.quantity * 1.15).toFixed(2) }}</span>
                </div>
                <div class="info-row">
                  <span class="label">卖家ID：</span>
                  <span class="value">{{ currentOrder.sellerId }}</span>
                </div>
                <div class="info-row">
                  <span class="label">订单状态：</span>
                  <span class="value" :class="{
                    'status-pending': currentOrder.orderStatus === 'pending',
                    'status-paid': currentOrder.orderStatus === 'paid',
                    'status-shipped': currentOrder.orderStatus === 'shipped',
                    'status-completed': currentOrder.orderStatus === 'completed',
                    'status-cancelled': currentOrder.orderStatus === 'cancelled',
                    'status-returned': currentOrder.orderStatus === 'returned'
                  }">
                    {{ getOrderStatusText(currentOrder.orderStatus) }}
                  </span>
                </div>
                <div class="info-row">
                  <span class="label">收货地址：</span>
                  <span class="value">{{ currentOrder.shippingAddress }}</span>
                </div>
              </div>
              
              <div class="product-images" v-if="getProductImages(currentOrder) && getProductImages(currentOrder).length > 0">
                <h4>商品图片</h4>
                <div class="image-gallery">
                  <img 
                    v-for="(image, index) in getProductImages(currentOrder)" 
                    :key="index"
                    :src="image"
                    alt="商品图片"
                    class="gallery-image"
                    @error="handleImageError"
                  />
                </div>
              </div>
              
              <div class="order-actions">
                <h4>操作</h4>
                <div class="action-buttons">
                  <template v-if="currentOrder.orderStatus === 'pending'">
                    <button @click="goToPayment(currentOrder)" class="submit-btn">去支付</button>
                    <button @click="cancelChooseOrder(currentOrder)" class="cancel-btn">取消订单</button>
                  </template>
                  <template v-else-if="currentOrder.orderStatus === 'paid'">
                    <button @click="confirmReceipt(currentOrder)" class="submit-btn">确认收货</button>
                    <button @click="returnProduct(currentOrder)" class="cancel-btn">退货</button>
                  </template>
                  <template v-else-if="currentOrder.orderStatus === 'shipped'">
                    <button @click="confirmReceipt(currentOrder)" class="submit-btn">确认收货</button>
                    <button @click="returnProduct(currentOrder)" class="cancel-btn">退货</button>
                  </template>
                  <template v-else-if="currentOrder.orderStatus === 'completed'">
                    <button @click="returnProduct(currentOrder)" class="cancel-btn">退货</button>
                  </template>
                  <button @click="backToOrders()" class="back-btn">返回订单列表</button>
                </div>
              </div>
            </div>
            <div v-else class="no-order">
              未选择订单
            </div>
           </div>


           <!-- 从下单界面跳转的支付界面（点击下单按钮后显示） -->
           <div v-if="activeTab === 'payF'" class="business-card">
            <h3>支付界面</h3>
            <div class="payment-info">
              <p><strong>商品名称：</strong>{{ selectedProduct?.productName }}</p>
              <p><strong>价格：</strong>¥{{ totalPrice }}（{{ selectedProduct?.unitPrice }} × {{ orderForm.quantity }} + 15%服务费）</p>
            </div>
            <div class="payment-actions">
              <button @click="confirmPaymentF" class="submit-btn">确认支付</button>
              <button @click="cancelPaymentF" class="cancel-btn">取消支付</button>
            </div>
           </div>

           <!-- 从已下单界面跳转的支付界面（点击去支付后显示） -->
           <div v-if="activeTab === 'pay'" class="business-card">
            <h3>支付界面</h3>
            <div class="payment-info">
              <p><strong>商品名称：</strong>{{ selectedProduct?.productName }}</p>
              <p><strong>价格：</strong>¥{{ totalPrice }}（{{ selectedProduct?.unitPrice }} × {{ orderForm.quantity }} + 15%服务费）</p>
            </div>
            <div class="payment-actions">
              <button @click="confirmPayment" class="submit-btn">确认支付</button>
              <button @click="cancelPayment" class="cancel-btn">取消支付</button>
            </div>
           </div>


          
        </el-main>
      </el-container>
    </el-container>
  </div>
</template>

<script>
import { useAuthStore } from '../stores/auth'
import ApiService from '../services/api'
import { CaretLeft, CaretRight } from '@element-plus/icons-vue'

export default {
  name: 'BuyerView',
  setup() {
    const authStore = useAuthStore()
    return { authStore }
  },
  data() {
    return {
      activeTab: 'placeOrder',
      currentOrder: null, // 当前查看的订单
      shippingAddress: '', // 模拟收货地址
      changePasswordForm: {
        accountId: '',
        oldPassword: '',
        newPassword: ''
      },
      orderForm: {
        goodsId: '',
        productName: '',
        quantity: 1,
        unit_price: '',
        sellerId: '',
        address: '',
        order_status: 'pending'
      },
      apiService: new ApiService('buyer'),
      availableProducts: [],
      loadingProducts: false,
      selectedProduct: null,
      showOrderForm: false,
      currentPage: 1,
      pageSize: 5,
      CaretLeft,
      CaretRight,
      // 已下单商品相关数据
      orderedGoods: [],
      loadingOrders: false,
      currentOrderPage: 1,
      orderPageSize: 5
    }
  },
  computed: {
    // 计算商品列表总页数
    totalPages() {
      return Math.ceil(this.availableProducts.length / this.pageSize)
    },
    // 计算当前页显示的商品
    paginatedProducts() {
      const startIndex = (this.currentPage - 1) * this.pageSize
      const endIndex = startIndex + this.pageSize
      return this.availableProducts.slice(startIndex, endIndex)
    },
    // 计算已下单商品总页数
    totalOrderPages() {
      return Math.ceil(this.orderedGoods.length / this.orderPageSize)
    },
    // 计算当前页显示的已下单商品
    paginatedOrders() {
      const startIndex = (this.currentOrderPage - 1) * this.orderPageSize
      const endIndex = startIndex + this.orderPageSize
      return this.orderedGoods.slice(startIndex, endIndex)
    }
  },
  mounted() {
    this.authStore.initAuth()
    if (this.authStore.isLoggedIn) {
      // 自动填充当前登录账号
      this.orderForm.accountId = this.authStore.accountId
      this.changePasswordForm.accountId = this.authStore.accountId
      
      // 根据当前激活的标签页加载对应数据
      if (this.activeTab === 'showGoodsInfo') {
        this.loadOrderedGoods()
      } else {
        // 加载商品列表
        this.loadAvailableProducts()
      }
    }
  },
  
  watch: {
    // 监听标签页变化，当切换到查看已下单商品时加载数据
    activeTab(newTab) {
      if (newTab === 'showGoodsInfo' && this.authStore.isLoggedIn) {
        this.loadOrderedGoods()
      }
    }
  },
  methods: {
    async handleChangePassword() {
      try {
        const result = await this.apiService.changePassword(
          this.changePasswordForm.accountId,
          this.changePasswordForm.oldPassword,
          this.changePasswordForm.newPassword
        )
        alert(result.message)
      } catch (error) {
        alert('修改密码出错')
      }
    },
    
    // 加载已上架商品列表
    async loadAvailableProducts() {
      this.loadingProducts = true
      try {
        const result = await this.apiService.getAvailableProducts()
        if (result.message === '获取成功') {
          this.availableProducts = result.products || []
          this.currentPage = 1 // 重置到第一页
        } else {
          alert('获取商品列表失败: ' + result.message)
        }
      } catch (error) {
        alert('加载商品列表出错')
        console.error('加载商品列表出错:', error)
      } finally {
        this.loadingProducts = false
      }
    },
    
    // 选择商品
    selectProduct(product) {
      this.selectedProduct = product
      this.orderForm.goodsId = product.listingId
      this.orderForm.productName = product.productName
      this.orderForm.unit_price = product.unitPrice
      this.orderForm.sellerId = product.sellerId
      this.showOrderForm = true // 显示下单表单
    },
    
    // 获取商品图片数组
    getProductImages(product) {
      // 兼容前后端字段命名差异
      const productImages = product.productImages || product.product_images
      const images = [];
      
      if (productImages) {
        try {
          // 根据数据库结构，product_images是varchar(100)，存储单个图片URL
          if (typeof productImages === 'string') {
            // 首先尝试作为JSON数组解析（兼容后端可能的返回格式）
            try {
              const parsedImages = JSON.parse(productImages);
              if (Array.isArray(parsedImages)) {
                parsedImages.forEach(image => {
                  if (typeof image === 'string') {
                    images.push(this.formatImageUrl(image));
                  }
                });
              } else {
                // 如果不是数组，当作单个图片URL处理
                images.push(this.formatImageUrl(productImages));
              }
            } catch (jsonError) {
              // 如果不是有效的JSON，直接作为单个图片URL处理
              images.push(this.formatImageUrl(productImages));
            }
          }
          // 如果已经是数组，处理每个图片URL
          else if (Array.isArray(productImages)) {
            productImages.forEach(image => {
              if (typeof image === 'string') {
                images.push(this.formatImageUrl(image));
              }
            });
          }
        } catch (e) {
          console.error('解析商品图片出错:', e);
        }
      }
      return images;
    },
    
    // 格式化图片URL
    formatImageUrl(imagePath) {
      // 如果图片路径已经是完整URL，则直接返回
      if (imagePath.startsWith('http')) {
        return imagePath;
      }
      // 如果是相对路径，则添加基础路径
      if (imagePath.startsWith('/')) {
        return `http://localhost:8080${imagePath}`;
      }
      // 其他情况，添加基础路径
      return `http://localhost:8080/img/${imagePath}`;
    },
    
    // 加载已下单商品列表
    async loadOrderedGoods() {
      this.loadingOrders = true
      try {
        // 调用API获取已下单商品
        console.log('调用API获取已下单商品，buyerId:', this.authStore.accountId)
        const result = await this.apiService.getPlacedProducts(this.authStore.accountId)
        console.log('API返回结果:', result)
        if (result && result.message === '获取成功') {
          // 将后端返回的listProduct对象转换为前端需要的格式
          this.orderedGoods = result.products ? result.products.map(product => ({
            orderId: product.transactionId, // 后端使用transactionId作为订单ID
            productName: product.productName,
            productDescription: product.productDescription,
            unitPrice: product.unitPrice,
            quantity: product.quantity,
            sellerId: product.sellerId,
            orderStatus: product.orderStatus,
            shippingAddress: product.shippingAddress || '', // 添加收货地址字段
            productImages: product.productImages || []
          })).sort((a, b) => {
            // 按orderId降序排序，让最近下单的订单显示在前面
            // 假设transactionId是按时间顺序生成的
            return b.orderId.localeCompare(a.orderId)
          }) : []
        } else {
          alert('获取已下单商品失败: ' + (result ? result.message : '未知错误'))
        }
        
        this.currentOrderPage = 1 // 重置到第一页
      } catch (error) {
        alert('加载已下单商品出错')
        console.error('加载已下单商品出错:', error)
      } finally {
        this.loadingOrders = false
      }
    },
    
    // 查看订单详情
    viewOrderDetail(order) {
      this.currentOrder = order
      this.activeTab = 'orderDetail'
    },
    
    // 返回订单列表
    backToOrders() {
      this.activeTab = 'showGoodsInfo'
      this.currentOrder = null
    },
    
    // 去支付
    goToPayment(order) {
      this.selectedProduct = {
        productName: order.productName,
        unitPrice: order.unitPrice
      }
      this.orderForm.quantity = order.quantity
      this.totalPrice = (order.unitPrice * order.quantity * 1.15).toFixed(2)
      this.currentOrder = order // 设置当前订单，用于支付时获取orderId
      this.activeTab = 'pay'
    },
    
        // 确认收货
    confirmReceipt(order) {
      if (confirm('确定要确认收货吗？')) {
        //传入内容要包括transactionId和buyerId
        this.apiService.confirmReceipt({
          transactionId: order.orderId,
          buyerId: this.authStore.accountId
        })
        .then(response => {
          console.log('后端返回的完整响应:', response);
          alert('确认收货成功！')
          this.backToOrders()
          this.loadOrderedGoods() // 重新加载订单列表
        })
        .catch(error => {
          alert('确认收货出错')
          console.error('确认收货出错:', error)
          this.backToOrders()
          this.loadOrderedGoods()
        }) 
      }
    },

    // 取消订单
    cancelChooseOrder(order) {
      if (confirm('确定要取消订单吗？')) {
        //传入内容要包括transactionId和buyerId
        this.apiService.cancelOrder({
          transactionId: order.orderId,
          buyerId: this.authStore.accountId
        })
        .then(response => {
          console.log('后端返回的完整响应:', response);
          alert('取消订单成功！')   
          this.backToOrders()
          this.loadOrderedGoods() // 重新加载订单列表
        })
        .catch(error => {
          alert('取消订单出错')
          console.error('取消订单出错:', error)
          this.backToOrders()
          this.loadOrderedGoods()
        })
      }
    },
    
    // 退货
    returnProduct(order) {
      if (confirm('确定要退货吗？')) {  
        //传入内容要包括transactionId和buyerId
        this.apiService.returnProduct({
          transactionId: order.orderId,
          buyerId: this.authStore.accountId
        })
        .then(response => {
          console.log('后端返回的完整响应:', response);
          alert('退货申请成功！')
          this.backToOrders()
          this.loadOrderedGoods() // 重新加载订单列表
        })
        .catch(error => {
          alert('退货申请出错')
          console.error('退货申请出错:', error)
          this.backToOrders()
          this.loadOrderedGoods()
        })
      }
    },
    
    // 上一页（已下单商品）
    prevOrderPage() {
      if (this.currentOrderPage > 1) {
        this.currentOrderPage--
      }
    },
    
    // 下一页（已下单商品）
    nextOrderPage() {
      if (this.currentOrderPage < this.totalOrderPages) {
        this.currentOrderPage++
      }
    },
    
    // 处理图片加载错误
    handleImageError(event) {
      event.target.src = '';
    },
    
    // 取消下单
    cancelOrder() {
      this.showOrderForm = false
      this.selectedProduct = null
      this.orderForm = {
        goodsId: '',
        productName: '',
        quantity: 1,
        unit_price: '',
        sellerId: '',
        address: '',
        order_status: 'pending'
      }
    },
    
    // 上一页
    prevPage() {
      if (this.currentPage > 1) {
        this.currentPage--
      }
    },
    
    // 下一页
    nextPage() {
      if (this.currentPage < this.totalPages) {
        this.currentPage++
      }
    },
    
    // 格式化日期
    formatDate(dateString) {
      if (!dateString) return ''
      const date = new Date(dateString)
      return date.toLocaleDateString('zh-CN')
    },
    
    // 计算总价格（商品数量*单价*15%服务费）
    get totalPrice() {
      if (!this.selectedProduct || !this.orderForm.quantity) return 0
      const basePrice = this.selectedProduct.unitPrice * this.orderForm.quantity
      const serviceFee = basePrice * 0.15 // 15%服务费
      return (basePrice + serviceFee).toFixed(2)
    },
    
    // 下单 - 创建新订单
    async handlePlaceOrder() {
      // 验证必填字段
      if (!this.orderForm.goodsId) {
        alert('请先选择商品')
        return
      }
      
      try {
        // 准备下单数据
        // const orderData = {
        //   productName: this.orderForm.productName,
        //   quantity: this.orderForm.quantity,
        //   unit_price: this.orderForm.unit_price,
        //   sellerId: this.orderForm.sellerId,
        //   buyerId: this.authStore.accountId,
        //   order_status:'',
        //   shipping_address: this.orderForm.address,
        //   payment_method: this.orderForm.payment_method
        // }
        
        // // 调用下单接口创建新订单
        // const result = await this.apiService.placeOrder(orderData)
        // alert(result.message)
        
          // 跳转到支付界面
          this.activeTab = 'payF'
        
      } catch (error) {
        alert('下单出错')
        console.error('下单出错:', error)
      }
    },
    
    // 在下单界面跳转的确认支付
    async confirmPaymentF() {
      //逻辑为将orderData中的order_status设置为paid，然后使用apiService.placeOrder(orderData)更新订单状态
      const orderData = {
          productName: this.orderForm.productName,
          quantity: this.orderForm.quantity,
          unit_price: this.orderForm.unit_price,
          sellerId: this.orderForm.sellerId,
          buyerId: this.authStore.accountId,
          order_status: 'paid',
          shipping_address: this.orderForm.address
        }
      
      try {
        const result = await this.apiService.placeOrder(orderData)
        alert(result.message)
        if (result.message === '下单成功') {
          // 清空表单
          this.cancelOrder()
          // 重新加载订单列表
          this.loadOrderedGoods()
          // 返回订单列表
          this.activeTab = 'showGoodsInfo'
        }
      } catch (error) {
        alert('支付出错')
        console.error('支付出错:', error)
      }
    },
    
    // 取消支付
    async cancelPaymentF() {
      //逻辑为将orderData中的order_status设置为pending，然后使用apiService.placeOrder(orderData)更新订单状态
      const orderData = {
          productName: this.orderForm.productName,
          quantity: this.orderForm.quantity,
          unit_price: this.orderForm.unit_price,
          sellerId: this.orderForm.sellerId,
          buyerId: this.authStore.accountId,
          order_status: 'pending',
          shipping_address: this.orderForm.address
        }
      try {
        const result = await this.apiService.placeOrder(orderData)
        alert(result.message)
        if (result.message === '下单成功') {
          // 清空表单
          this.cancelOrder()
          // 重新加载订单列表
          this.loadOrderedGoods()
          // 返回订单列表
          this.activeTab = 'showGoodsInfo'
        }
      } catch (error) {
        alert('支付出错')
        console.error('支付出错:', error)
      }
    },



    //在已下单界面的确认支付
    async confirmPayment() {
      //逻辑为获取已选择的商品的TransactionIdTransactionId和买家id
      const credentials = {
        transactionId: this.currentOrder.orderId,  
        buyerId: this.authStore.accountId,         
      }
      // 调用确认支付接口
      try {
        const result = await this.apiService.pay(credentials)
        alert(result.message)
        if (result.message === '支付成功') {
          // 清空表单
          this.cancelOrder()
          // 重新加载订单列表
          this.loadOrderedGoods()
          // 返回订单列表
          this.activeTab = 'showGoodsInfo'
        }
      } catch (error) {
        alert('支付出错')
        console.error('支付出错:', error)
      }
    },
    
    // 取消支付
    async cancelPayment() {
      // 根据来源判断返回页面
      if (this.currentOrder && this.currentOrder.orderId) {
        // 如果有订单ID，说明是从订单详情页来的，返回订单详情
        this.activeTab = 'orderDetail'
      } else {
        // 如果没有订单ID，说明是从下单界面来的，清空表单并返回下单界面
        this.cancelOrder()
        this.activeTab = 'placeOrder'
      }
      alert('支付已取消')
    },



    
    handleLogout() {
      this.authStore.setLogout()
      // 恢复到登录面板并清理本页数据
      this.activeTab = 'placeOrder'
      this.changePasswordForm = { accountId: '', oldPassword: '', newPassword: '' }
      // 清理商品与下单相关状态
      this.availableProducts = []
      this.loadingProducts = false
      this.selectedProduct = null
      this.showOrderForm = false
      this.orderForm = { goodsId: '', productName: '', quantity: 1, unit_price: '', sellerId: '', address: '', order_status: 'pending' }
      this.currentPage = 1
      // 清除后端 cookie
      document.cookie = 'accountId=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;'
      // 跳转回主界面
      try { this.$router.push('/') } catch (e) { window.location.href = '/' }
    },
      // 获取订单状态的中文显示
      getOrderStatusText(status) {
        const statusMap = {
          'pending': '待支付',
          'paid': '已支付',
          'shipped': '已发货',
          'completed': '已完成',
          'cancelled': '已取消',
          'returned': '已退货'
        }
        return statusMap[status] || status
      },
    
    goHome() {
      // 未登录时点击回到主界面
      try { this.$router.push('/') } catch (e) { window.location.href = '/' }
    }
  }
}
</script>

<style scoped>
/* 新色彩主题 */
:root {
  /* 主色调 - 现代蓝色系 */
  --primary-color: #409EFF;
  --primary-light: #ecf5ff;
  --primary-dark: #3375b9;
  
  /* 辅助色 */
  --success-color: #67C23A;
  --warning-color: #E6A23C;
  --danger-color: #F56C6C;
  --info-color: #909399;
  
  /* 中性色 - 更柔和的灰色 */
  --text-primary: #2c3e50;
  --text-regular: #5a6c7d;
  --text-secondary: #8796a8;
  --text-placeholder: #c0c8d1;
  
  /* 背景色 - 渐变效果 */
  --bg-gradient: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  --bg-card: #ffffff;
  --bg-sidebar: linear-gradient(180deg, #304156 0%, #1f2d3d 100%);
  
  /* 边框色 */
  --border-color: #e4e7ed;
  --border-light: #ebeef5;
  --border-lighter: #f2f6fc;
  
  /* 阴影 */
  --shadow-card: 0 4px 20px rgba(0, 0, 0, 0.08);
  --shadow-hover: 0 6px 24px rgba(0, 0, 0, 0.1);
  --shadow-header: 0 2px 12px rgba(0, 0, 0, 0.1);
}

/* 整体布局 */
.common-layout {
  height: 100vh;
  width: 100vw;
  background: var(--bg-gradient);
}

.el-container {
  height: 100%;
}

/* 顶部导航栏 */
.el-header {
  background: #ffffff;
  box-shadow: var(--shadow-header);
  display: flex;
  align-items: center;
  padding: 0 24px;
  border-bottom: 1px solid var(--border-color);
  height: 0px;
  line-height: 60px;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  height: 100%;
  box-sizing: border-box;
  padding: 0 24px;
}

.header-content h2 {
  margin: 0;
  color: var(--text-primary);
  font-size: 18px;
  font-weight: 600;
}

.header-user-info {
  color: var(--text-regular);
  font-size: 14px;
}

/* 侧边栏 */
.el-aside {
  background: var(--bg-sidebar);
  box-shadow: 2px 0 8px 0 rgba(29, 35, 41, 0.1);
  overflow-y: auto;
}

.sidebar-header {
  padding: 20px;
  border-bottom: 1px solid #2d3a4b;
  color: white;
  text-align: center;
}

.sidebar-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
}

.sidebar-menu {
  padding: 16px 0;
}

.menu-item {
  width: 100%;
  padding: 12px 24px;
  border: none;
  background: transparent;
  color: rgba(255, 255, 255, 0.7);
  text-align: left;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s ease;
  display: block;
}

.menu-item:hover {
  background: rgba(255, 255, 255, 0.1);
  color: #ffffff;
}

.menu-item.active {
  background: var(--primary-color);
  color: #ffffff;
}

.sidebar-login-prompt {
  padding: 20px;
  text-align: center;
}

.back-home-tab {
  padding: 10px 20px;
  margin: 10px auto;
  border: 1px solid var(--primary-color);
  background: transparent;
  color: var(--primary-color);
  cursor: pointer;
  display: block;
  width: 100%;
  border-radius: 4px;
  font-size: 14px;
  transition: all 0.3s ease;
}

.back-home-tab:hover {
  background: var(--primary-color);
  color: white;
}

.sidebar-footer {
  margin-top: auto;
  /* 上边距20px */
  margin-top:300%;
  padding: 16px;
  width: 100%;
  box-sizing: border-box;
}

.logout-btn {
  width: 80%;
  margin: 0 auto;
  display: block;
  padding: 10px 20px;
  border: none;
  background: var(--danger-color);
  color: white;
  cursor: pointer;
  border-radius: 4px;
  font-size: 14px;
  transition: all 0.3s ease;
}

.logout-btn:hover {
  background: #e4393c;
}

/* 主内容区 */
.el-main {
  padding: 24px;
  overflow-y: auto;
  background: transparent;
}

.main-content {
  min-height: 100%;
}

/* 业务卡片 */
.business-card {
  background: var(--bg-card);
  border-radius: 8px;
  box-shadow: var(--shadow-card);
  padding: 24px;
  margin-bottom: 20px;
  transition: all 0.3s ease;
  border: 1px solid var(--border-light);
}

.business-card:hover {
  transform: translateY(-2px);
  box-shadow: var(--shadow-hover);
}

.business-card h3 {
  color: var(--text-primary);
  margin-bottom: 20px;
  font-size: 18px;
  font-weight: 600;
}

/* 表单样式 */
.business-card form {
  max-width: 400px;
  margin: 0 auto;
}

.business-card input, .business-card textarea, .business-card select {
  width: 100%;
  padding: 10px;
  margin: 10px 0;
  border: 1px solid var(--border-color);
  border-radius: 4px;
  transition: border-color 0.3s ease;
}

.business-card input:focus, .business-card textarea:focus, .business-card select:focus {
  outline: none;
  border-color: var(--primary-color);
}

.business-card button[type="submit"] {
  width: 100%;
  padding: 10px;
  background: var(--primary-color);
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 16px;
  transition: background-color 0.3s ease;
}

.business-card button[type="submit"]:hover {
  background: var(--primary-dark);
}

/* 商品列表样式 */
.products-section {
  margin-bottom: 2rem;
}

.products-section h4 {
  margin-bottom: 1rem;
  color: var(--text-primary);
  font-size: 16px;
  font-weight: 600;
}

.loading, .no-products {
  text-align: center;
  padding: 2rem;
  color: var(--text-secondary);
  background: var(--border-lighter);
  border-radius: 8px;
}

/* 商品表格 */
.products-table {
  width: 100%;
  border-collapse: collapse;
  margin-bottom: 1rem;
  background: white;
  box-shadow: 0 1px 3px rgba(0,0,0,0.1);
  border-radius: 8px;
  overflow: hidden;
}

.products-table th,
.products-table td {
  border: 1px solid var(--border-color);
  padding: 12px;
  text-align: left;
}

.products-table th {
  background-color: #f5f5f5;
  font-weight: bold;
  color: var(--text-primary);
}

.products-table tr:nth-child(even) {
  background-color: var(--border-lighter);
}

.products-table tr:hover {
  background-color: var(--border-light);
}

/* 商品图片样式 */
.product-images {
  display: flex;
  flex-wrap: wrap;
  gap: 5px;
  min-height: 50px;
  align-items: center;
}

.product-image {
  max-width: 80px;
  max-height: 80px;
  object-fit: cover;
  border-radius: 4px;
  border: 1px solid var(--border-light);
}

.no-image {
  color: var(--text-placeholder);
  font-size: 12px;
  padding: 5px;
  text-align: left;
}

/* 按钮样式 */
.select-btn {
  background: var(--primary-color);
  color: white;
  border: none;
  padding: 6px 12px;
  border-radius: 3px;
  cursor: pointer;
  font-size: 12px;
  transition: background-color 0.3s ease;
}

.select-btn:hover {
  background: var(--primary-dark);
}

/* 分页样式 */
.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 1rem;
  gap: 1rem;
}

.pagination-btn {
  padding: 8px 16px;
  border: 1px solid var(--border-color);
  background: white;
  cursor: pointer;
  border-radius: 4px;
  font-size: 14px;
  transition: all 0.3s ease;
}

.pagination-btn:disabled {
  background: #f5f5f5;
  color: var(--text-placeholder);
  cursor: not-allowed;
}

.pagination-btn:not(:disabled):hover {
  background: var(--primary-color);
  color: white;
  border-color: var(--primary-color);
}

.page-info {
  color: var(--text-regular);
  font-weight: bold;
  font-size: 14px;
}

/* 不需要专门的图标样式了 */

/* 订单详情样式 */
.order-detail {
  background-color: #f9f9f9;
  padding: 20px;
  border-radius: 8px;
  margin-top: 20px;
}

.order-info {
  margin-bottom: 20px;
}

.order-info h4 {
  margin-bottom: 15px;
  color: #333;
  border-bottom: 1px solid #ddd;
  padding-bottom: 8px;
}

.info-row {
  display: flex;
  margin-bottom: 12px;
  align-items: flex-start;
}

.info-row .label {
  font-weight: bold;
  width: 120px;
  color: #555;
}

.info-row .value {
  flex: 1;
  color: #333;
}

.product-images {
  margin-bottom: 20px;
}

.product-images h4 {
  margin-bottom: 15px;
  color: #333;
  border-bottom: 1px solid #ddd;
  padding-bottom: 8px;
}

.image-gallery {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

.gallery-image {
  width: 100px;
  height: 100px;
  object-fit: cover;
  border-radius: 4px;
  border: 1px solid #ddd;
}

.order-actions {
  margin-bottom: 20px;
}

.order-actions h4 {
  margin-bottom: 15px;
  color: #333;
  border-bottom: 1px solid #ddd;
  padding-bottom: 8px;
}

.action-buttons {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

.action-buttons button {
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-weight: bold;
  transition: background-color 0.3s;
}

.action-buttons button:disabled {
  background-color: #ccc;
  cursor: not-allowed;
  opacity: 0.6;
}

.detail-btn {
  padding: 6px 12px;
  background-color: #4CAF50;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: background-color 0.3s;
}

.detail-btn:hover {
  background-color: #45a049;
}

.no-order {
  text-align: center;
  padding: 40px;
  color: #666;
  font-size: 16px;
}

.back-btn {
  background-color: #f0f0f0;
  color: #333;
}

.back-btn:hover {
  background-color: #e0e0e0;
}

/* 下单表单样式 */
.order-form-container {
  margin-top: 2rem;
  padding: 20px;
  border: 1px solid var(--border-color);
  border-radius: 8px;
  background: white;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.order-form-container h4 {
  margin-bottom: 1.5rem;
  color: var(--text-primary);
  text-align: center;
  font-size: 16px;
  font-weight: 600;
}

.order-form {
  max-width: 500px;
  margin: 0 auto;
}

.form-group {
  margin-bottom: 1.25rem;
}

.form-group label {
  display: block;
  margin-bottom: 0.5rem;
  font-weight: bold;
  color: var(--text-regular);
}

.form-group input, .form-group select {
  width: 100%;
  padding: 8px 12px;
  border: 1px solid var(--border-color);
  border-radius: 4px;
  transition: border-color 0.3s ease;
}

.form-group input:focus, .form-group select:focus {
  outline: none;
  border-color: var(--primary-color);
}

.form-group input[readonly] {
  background-color: var(--border-lighter);
  color: var(--text-secondary);
}

.form-actions {
  display: flex;
  gap: 1rem;
  margin-top: 1.5rem;
}

.submit-btn {
  flex: 2;
  padding: 10px;
  background: var(--success-color);
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 16px;
  transition: background-color 0.3s ease;
}

.submit-btn:hover {
  background: #5daf34;
}

.cancel-btn {
  padding: 10px;
  background: var(--danger-color);
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 16px;
  transition: background-color 0.3s ease;
}

.cancel-btn:hover {
  background: #e4393c;
}

/* 支付界面样式 */
.payment-info {
  background: var(--primary-light);
  padding: 15px;
  border-radius: 4px;
  margin-bottom: 20px;
}

.payment-info p {
  margin: 10px 0;
  color: var(--text-primary);
}

.payment-actions {
  display: flex;
  gap: 10px;
  margin-top: 20px;
}

.payment-actions button {
  flex: 1;
  padding: 12px;
  font-size: 16px;
  font-weight: 600;
}

/* 订单状态样式 */
  .status-pending {
    color: var(--warning-color);
    font-weight: 600;
  }
  
  .status-paid {
    color: var(--success-color);
    font-weight: 600;
  }
  
  .status-shipped {
    color: #9c27b0;
    font-weight: 600;
  }
  
  .status-completed {
    color: #4caf50;
    font-weight: 600;
  }
  
  .status-cancelled {
    color: #f44336;
    font-weight: 600;
  }
  
  .status-returned {
    color: #795548;
    font-weight: 600;
  }
  
  /* 禁用按钮样式 */
  button:disabled {
    opacity: 0.6;
    cursor: not-allowed;
  }

/* 登录提示 */
  .login-prompt {
  color: var(--warning-color);
  font-size: 14px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .el-container {
    grid-template-columns: 1fr;
    grid-template-rows: 60px 1fr;
    grid-template-areas: 
      "header"
      "main";
  }
  
  .el-aside {
    display: none; /* 移动端隐藏侧边栏 */
  }
  
  .el-main {
    padding: 16px;
  }
  
  .header-content {
    flex-direction: column;
    gap: 10px;
    padding: 10px 0;
  }
  
  .business-card {
    padding: 16px;
  }
  
  .form-actions {
    flex-direction: column;
  }
}
</style>